// import { download } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";
import router from "/@/router/index";
import { storageLocal } from "/@/utils/storage";
// import { downloadFile } from "./ecm";
import axios from "axios";

export const uploadUrl =
  import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";

export const uploadUrlImport =
  import.meta.env.VITE_BASE_URL + "/snow-admin/qtyCheck/importInsContent";

const FileTypes = {
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  pdf: "application/pdf",
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  ppt: "application/vnd.ms-powerpoint",
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
};

const xlsxFile = {
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};

const imageFile = {
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg"
};

export const acceptTypes = Object.values(FileTypes).join(",");
export const acceptXlsxTypes = Object.values(xlsxFile).join(",");
export const acceptImageTypes = Object.values(imageFile).join(",");
export const uploadHeaders = () => {
  return {
    Authorization: storageLocal.getItem("info")?.accessToken,
    loginMethod: "PC"
  };
};

export const handlePreview = item => {
  if (item.response) {
    // let el=item.response.data
    window.open(
      `${location.origin}${location.pathname}#/preview?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
    );
  } else {
    window.open(
      `${location.origin}${location.pathname}#/preview?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
    );
  }
  // if (file?.response?.code === 200 && file?.response?.data) {
  //   download(file?.response?.data);
  // } else if (file?.uuidFile && file.uuidFile.indexOf("gns") === -1) {
  //   download(file);
  // } else {
  //   downloadFile(file.uuidFile, file.name);
  // }
};

export const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);

  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);
    router.push("/login");
    storageLocal.removeItem("info");
  }
};

export const beforeAvatarUpload = file => {
  // const type = file.type.slice(file.type.lastIndexOf("/") + 1);
  const type = file.name
    .substring(file.name.lastIndexOf(".") + 1)
    .toLocaleLowerCase();
  if (!Object.keys(FileTypes).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(FileTypes).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};

export const beforeXmlUpload = file => {
  const type = file.name
    .substring(file.name.lastIndexOf(".") + 1)
    .toLocaleLowerCase();
  if (!Object.keys(xlsxFile).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(xlsxFile).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};

export const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return [];
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

export const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return [];
  const newFileData = list.map(item => {
    if (item.response) {
      item.response.data["name"] = item.response.data.fileName;
      return item.response && item.response.data;
    }
    item["name"] = item.fileName;
    return item;
    // }
  });
  return newFileData;
};

/**
 * URL方式保存文件到本地
 * @param name 文件名
 * @param data 文件的数据
 */
function save(name, data) {
  const urlObject: any = window.URL || window.webkitURL;
  const export_blob = new Blob([data]);
  let save_link: HTMLAnchorElement = document.createElement("a");
  save_link.href = urlObject.createObjectURL(export_blob);
  save_link.download = name;
  save_link.click();
  urlObject.revokeObjectURL(save_link.href);
  save_link = null;
}

export function downloadUrlFile(url: string, name: string) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = () => {
    if (xhr.status == 200) {
      // 获取图片blob数据并保存
      save(name, xhr.response);
    }
  };

  xhr.send();
}

export function fileToBase64(file) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.readAsDataURL(file.raw);
    reader.onload = e => {
      return resolve(e.target.result);
    };
  });
}

export function base64ToFile(base64, filename) {
  const arr = base64.split(",");
  const type = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: type });
}

// 导出文件
export function exportExcel(downloadUrl, formData, filename) {
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      loginMethod: "PC",
      Authorization: storageLocal.getItem("info").accessToken
    }
  })
    .then(res => {
      const data = res.data;
      const date = new Date();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const dateTime = `${date.getFullYear()}${
        month < 10 ? "0" + month : month
      }${day < 10 ? "0" + day : day}`;
      const filenames = `${filename}-${dateTime}.xlsx`;
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.setAttribute("download", `${filenames}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          const reader: any = new FileReader();
          reader.readAsText(err.response.data, "utf-8");
          reader.addEventListener("loadend", () => {
            const res = JSON.parse(reader.result);
            NotifMessage.error(res.message);
          });
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log("err", err.request);
      } else {
        console.log("err", err.message);
      }
    });
}
